﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Spring.Objects;
using NHibernate;
using com.pro2e.web.config.init;
using com.pro2e.console.core.hibernate;

/// <summary>
/// VersionService 的摘要描述
/// </summary>
/// 
namespace com.pro2e.console.generic.staledata
{

    public class VersionService
    {
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public VersionService()
        {
          
        }

        /// <summary>
        /// 檢查是否版本相同
        /// </summary>
        /// <param name="o">檢查的物件</param>
        /// <param name="key">key值</param>
        public void CheckVersion(object o, object key)
        {

            IObjectWrapper owComp = new ObjectWrapper(o);
            Object objVersion = owComp.GetPropertyValue("Version");

            if (objVersion == null)
            {
                return;
            }
            else
            {
                int version = int.Parse(objVersion.ToString());

                ISession newSession = WebApplication.SessionFactory.OpenSession();
                Object originalObject = newSession.Get(o.GetType(), key);
                newSession.Close();

                IObjectWrapper owComp2 = new ObjectWrapper(originalObject);
                int oriVersion = int.Parse(owComp2.GetPropertyValue("Version").ToString());

                log.Debug(String.Format("original Version={0}, new Version={1}", oriVersion, version));

                if (oriVersion != version)
                {
                    ISession session = NHibernateSessionManager.Instance.GetSession();
                    session.Transaction.Rollback();
                    throw new StaleObjectStateException(null, key);
                }
            }

        }        
    }
}